﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using SuppKids.Core.Reporting.Data;

namespace SuppKids.Core.Reporting.Excel
{
    public abstract class ExcelReportGenerator : IReportGenerator
	{
		public ReportFormat ReportFormat
		{
			get { return ReportFormat.Excel; }
		}

		public void GenerateReport(IReportData reportData, Stream targetStream)
		{
			SaveToStream(this.CreateContent, reportData, targetStream);
		}

        protected IFormatProvider FormatProvider
        {
            // todo: need to move this culture to configuration file
            get
            {
                return new CultureInfo("ru-RU");
            }
        }

		protected abstract void CreateContent(IXLWorksheet worksheet, IReportData reportData);

		protected virtual void CreateWorkbook(out XLWorkbook workbook, out IXLWorksheet worksheet)
		{
			workbook = new XLWorkbook();
            worksheet = workbook.Worksheets.FirstOrDefault() ?? workbook.Worksheets.Add(workbook.Worksheets.Count.ToString(this.FormatProvider));
		}

		private void SaveToStream(Action<IXLWorksheet, IReportData> createContent, IReportData reportData, Stream targetStream)
		{
			XLWorkbook workbook;
			IXLWorksheet worksheet;
			this.CreateWorkbook(out workbook, out worksheet);

			createContent(worksheet, reportData);

            workbook.SaveAs(targetStream);
		}
	}
}
